(function(window){
	var ajaxUrl = "http://192.168.100.35:8099";

	/* 判断是否登录 */
	if(sessionStorage.getItem("userName")){

		/* 根据用户类型跳转到 首页或者管理页 */
		skip();
	}else{

		inputResult();

		$('#password').datetimepicker({
		    language: 'zh-CN',
		    weekStart: 1,
		    todayBtn: "linked",
		    autoclose: true,
		    clearBtn: true,
		    todayHighlight: true,
		    startView: 2,
		    minView: 2,
		    maxView: 4,
		    format: 'yyyy-mm-dd',

		    autoclose: 1,

		    initialDate: new Date(),

		    forceParse: 0,

		    container: 'body',

		    endDate: null
		});

		$("#loginButton").click(function(){
			var name = $("#name").val().trim();
			var date = $("#password").val().trim();

			if(name === ""){
				dialog("<span style='color: red'>请输入用户名！</span>");
				return;
			}

			var data = {
					name: name,
					mockDate: date
				}

			/* 登录 */
			$.ajax({
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(data),
				url: ajaxUrl + "/api/account",
				success: function(data){
					if(data.code === 1){
						var data = data.data;

						/* 存储 用户登录状态 */
						sessionStorage.setItem("userName", data.userInfo.userName);
						sessionStorage.setItem("userRole", data.userInfo.userRole);
						sessionStorage.setItem("maxim", JSON.stringify(data.motto));

						/* 根据用户角色跳转到 首页或者管理页 */
						skip();
					}else{
						dialog("<span style='color: red'>"+ data.msg +"</span>");
					}
				},
				error: function(){
					dialog("<span style='color: red'>登录失败</span>");
				}
			});
		});
	}

	/* 输入效果 */
	function inputResult(){
		var url = {
			normal: "images/normal.png",
			greeting: "images/greeting.png",
			blindfold: "images/blindfold.png"
		}

		var img = $("#img");

		$("#name").focus(function(){
			img.attr("src", url.greeting).css("top", -86);
		});
		$("#password").focus(function(){
			img.attr("src", url.blindfold).css("top", -75);
		});
		$("#name,#password").blur(function(){
			img.attr("src", url.normal).css("top", -80);
		});	
	}

	/* 弹框效果 */
	function dialog(msg){

		var html = '<li>' + msg + '</li>'
		$(".dialog").append(html);

		var lastLi = $(".dialog li:last");

		lastLi.fadeToggle("slow");

		setTimeout(function(){
			lastLi.fadeToggle("slow", function(){
				lastLi.remove();
			});
		}, 2000);
	}

	/* 跳转 */
	function skip(){

		var url = "";

		/* 获取 用户类型 */
		var userRole = sessionStorage.getItem("userRole");

		if(userRole === "0"){

			/* 管理员 */
			url = "html/administrator.html";
		}else{

			/* 普通用户 */
			url = "html/home.html";
		}

		/* 跳转页面 */
		window.location.href = url;
	}
})(window);

